<template>
	<div>
		<el-form>
			<el-form-item>
				<el-button type="primary" @click="onAddRole">新增角色</el-button>
			</el-form-item>
		</el-form>

		<el-table :data="roleList" border style="width: 100%">
			<el-table-column prop="roleId" label="角色id" width="180px"></el-table-column>
			<el-table-column prop="roleName" label="角色名称" width="180px"></el-table-column>
			<el-table-column label="操作">
				<template #default="scope">
					<el-button type="primary" size="small" @click="onChangeRole(scope.row)">修改权限</el-button>
				</template>
			</el-table-column>
		</el-table>
	</div>
</template>

<script lang="ts" setup>
import { ElMessageBox, ElMessage } from 'element-plus'
import { getRoleList } from '@/api/role'

interface IRoleItem {
	roleId: number
	roleName: string
	authority: number[]
}

const router = useRouter()

const roleList = ref<IRoleItem[]>([])

const onAddRole = () => {
	ElMessageBox.prompt('请输入角色名称', '添加角色', {
		confirmButtonText: '确认',
		cancelButtonText: '取消'
	})
		.then(({ value }) => {
			if (value) {
				roleList.value.push({
					roleId: roleList.value.length + 1,
					roleName: value,
					authority: []
				})
				ElMessage({
					message: `${value}角色添加成功`,
					type: 'success'
				})
			}
		})
		.catch(() => {
			ElMessage({
				message: '用户点击取消',
				type: 'info'
			})
		})
}

const onChangeRole = (role: IRoleItem) => {
	router.push({
		path: '/auth',
		query: {
			id: role.roleId,
			authority: role.authority
		}
	})
}

onMounted(() => {
	getRoleList().then((resp) => {
		roleList.value = resp
	})
})
</script>

<style scoped></style>
